package cn.com.open.opensaas.scoreservice.service.impl;

import cn.com.open.opensaas.baiscommon.common.ReturnModel;
import cn.com.open.opensaas.baiscommon.enums.ItemType;
import cn.com.open.opensaas.scoreservice.logic.QuestionJudgeFactory;
import cn.com.open.opensaas.baiscommon.model.question.AnswerQuestionLog;
import cn.com.open.opensaas.scoreservice.service.QuestionJudgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QuestionJudgeServiceImpl implements QuestionJudgeService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 判分
     * @param uniqueId 查询唯一标识
     * @return
     */
    @Override
    public ReturnModel judge(Long uniqueId) {
        ReturnModel returnModel = new ReturnModel();
        //存储试卷总分
        Double totalScore = 0.0;
        //用来存储Data关键值中的数据
        Map<String, Object> dataMap = new HashMap<>();
        //用来存储Data中Items关键值中的数据
        List<Map<String, Object>> itemList = new ArrayList<>();
        //创建判分工厂
        QuestionJudgeFactory questionJudgeFactory = new QuestionJudgeFactory();

        List<AnswerQuestionLog> answerQuestions = mongoTemplate.find(new Query(Criteria.where("uniqueId").is(uniqueId)), AnswerQuestionLog.class);

        for ( AnswerQuestionLog answerQuestion : answerQuestions) {
            //存储最终返回结果
            Map<String, Object> resultMap = new HashMap<>();
            questionJudgeFactory.judge(answerQuestion,resultMap);
            itemList.add(resultMap);
            //将每个section分值记入试卷总分
            totalScore += answerQuestion.getItems().get(0).getI16();
        }
        //存储dataMap数据
        dataMap.put(ItemType.TOTALSCORE.getDisplay(), totalScore);
        dataMap.put(ItemType.ITEMS.getDisplay(), itemList);
        returnModel.setData(dataMap);
        return returnModel;
    }


}
